package nl.moviefan.site.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import nl.moviefan.site.model.MoviefanRole;
import nl.moviefan.site.model.MoviefanUser;
import nl.moviefan.site.repository.UserRepository;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

/**
 * Service class for users.
 */
@Service
public class UserService {

    @Autowired
    private UserRepository userRepository;
    @Autowired
    private RoleService rolService;

    public Page<MoviefanUser> findAll(Pageable pageable) {
        return userRepository.findAll(pageable);
    }

    public MoviefanUser findByUsername(String username) {
        return userRepository.findByUsername(username);
    }

    public MoviefanUser save(MoviefanUser user) {
        //when registering a new user the user is activated (enabled = true)
        user.setEnabled(true);
//        user.setRegistrationDate(new Date());
        MoviefanUser userSaved = userRepository.save(user);

        if (user.getId() == -1) {
            setRolForUser(userSaved, "klant");
            return userRepository.save(userSaved);
        }
        return userSaved;
    }

    private void setRolForUser(MoviefanUser moviefanUser, String rolname) {
        List<MoviefanRole> rollen = moviefanUser.getMoviefanUserRoles();
        if (rollen == null) {
            rollen = new ArrayList<MoviefanRole>();
        }
        MoviefanRole klantRol = rolService.findByName(rolname);
        rollen.add(klantRol);
        moviefanUser.setMoviefanUserRoles(rollen);
    }
}
